<?php


namespace App\Component;


use Hyperf\Utils\ApplicationContext;

class UidBand
{

    use Singleton;

    private UidBandServerInterface $table1;
    private UidBandServerInterface $table2;


    /**
     * 支持动态注入和默认
     * UidBand constructor.
     * @param UidBandServerInterface ...$args
     */
    public function __construct(UidBandServerInterface ...$args)
    {
        if(func_num_args() >= 2){
            $this->table1 = func_get_arg(0);
            $this->table2 = func_get_arg(1);
        }else{
            //使用swooletable
//        $this->table1 = new SwooleTableUidBandServer(SwooleTable::getInstance()->get('fd_uid'), 'uid');
//        $this->table2 = new SwooleTableUidBandServer(SwooleTable::getInstance()->get('uid_fd'), 'fd');
            //使用redis
            $container = ApplicationContext::getContainer();
            $redis = $container->get(\Hyperf\Redis\Redis::class);
            $this->table1 = new RedisUidBandServer($redis, 'fd_uid');
            $this->table2 = new RedisUidBandServer($redis, 'uid_fd');
        }
    }


    /**
     * @param $fd
     * @param $uid
     */
    public function bindUid($fd, int $uid): void
    {
        $this->table1->set($fd, $uid);
        $this->table2->set($uid, $fd);
    }

    /**
     * @param $fd
     * @param $uid
     */
    public function unBindUid($fd, int $uid): void
    {
        $this->table1->del($fd);
        $this->table2->del($uid);
    }


    public function getUidByFd($fd)
    {
        return $this->table1->get($fd);
    }


    public function getFdByUid(int $uid): ?string
    {
        return $this->table2->get($uid);
    }


    public function isUidBand($uid): bool
    {
        return $this->table2->get($uid) != false;
    }


    public function isFdBand($fd): bool
    {
        return $this->table1->get($fd) != false;
    }

    public function clear()
    {
        $this->table1->clear();
        $this->table2->clear();
    }
}